package com.rp.system.dao;

import java.util.List;

import org.raptor.orm.hibernate.DbaHibernateTemplateSupport;
import org.raptor.pagination.Page2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import com.rp.common.vo.PageParam;
import com.rp.system.po.Task;

@Repository
public class TaskDao extends DbaHibernateTemplateSupport<Task> {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 分页获取任务列表
	 * @param pageParam
	 * @return
	 */
	public Page2 getTasksByPage(PageParam pageParam){
		String hql = "from Task";
		
		Page2 page = this.getPage2ByOffset(hql, 
				pageParam.getPageOffset(), pageParam.getPageSize(), 
				pageParam.getSortField(), pageParam.getSortOrder());
		List<Task> tasks = (List<Task>) page.getData();
		for (Task task : tasks) {
			String taskName = task.getTaskName();
			SqlRowSet rs = jdbcTemplate.queryForRowSet("select * from QRTZ_TRIGGERS t where t.JOB_NAME = ?", taskName);
			if(rs.next()){
				String status = rs.getString("TRIGGER_STATE");
				if(status.equals("COMPLETE")){
					jdbcTemplate.execute("UPDATE RP_SYSTEM_TASKS SET taskStatus = '"+Task.COMPLETE+"' WHERE taskName = '"+taskName+"'");
				}
			}
		}
		
		page.setData(tasks);
		
		return page;
	}
	
}
